package com.learn.springboot.config;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;

import javax.sql.DataSource;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.extra.spring.SpringUtil;

/**
 * @author suzheng
 * @date 2024-04-25
 **/
@Component
public class ApplicationReadyListener implements ApplicationListener<ApplicationReadyEvent>, InitializingBean {
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        initDbFile();
    }

    private void initDbFile() {
        String dbPath = AppConfig.getInstance().getSqliteDbPath();
        File destFile = FileUtil.newFile(dbPath);
        if (destFile.exists()) {
            return;
        }
        destFile.getParentFile().mkdirs();
        ClassPathResource classPathResource = new ClassPathResource("db.sqlite3");
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(destFile);
            IoUtil.copy(classPathResource.getInputStream(), fileOutputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        initDbFile();
        JdbcTemplate jdbcTemplate = new JdbcTemplate(SpringUtil.getBean(DataSource.class));
        String sql = IoUtil.read(ResourceUtil.getReader("init.sql", Charset.defaultCharset()));

        jdbcTemplate.execute(sql);

    }
}
